package localizer.main;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.Toast;


public class ExemploCameraActivity extends Activity {
    /** Called when the activity is first created. */
	String TAG  = "guthy gay";
	static String username;
	static String id;
    private SurfaceHolder hd;
    public Camera camera;
 
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if(camera!=null){
			camera.release();
		}
		camera=null;
	}
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.survace);
        username=Config.getInstance(this).getUsername(this);
        id=Config.getInstance(this).getID(this);
        camera = Camera.open();
        SurfaceView sv = (SurfaceView) findViewById(R.id.surfaceView1);
        hd = (SurfaceHolder) sv.getHolder();
        hd.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        hd.addCallback( new CameraPreview());
        try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
		}
    	camera.takePicture(null, null, jpegCallback);
    	
         
    }
    public class CameraPreview implements SurfaceHolder.Callback {


        public void surfaceCreated(SurfaceHolder holder) {
            // The Surface has been created, now tell the camera where to draw the preview.
            try {
                camera.setPreviewDisplay(holder);
                camera.startPreview();
                
            } catch (Exception e) {
                Log.d(TAG, "Error setting camera preview: " + e.getMessage());
            }
        }

        public void surfaceDestroyed(SurfaceHolder holder) {
            // empty. Take care of releasing the Camera preview in your activity.
        }

        public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
            // If your preview can change or rotate, take care of those events here.
            // Make sure to stop the preview before resizing or reformatting it.

            if (hd.getSurface() == null){
              // preview surface does not exist
              return;
            }

            // stop preview before making changes
            try {
                camera.stopPreview();
            } catch (Exception e){
              // ignore: tried to stop a non-existent preview
            }

            // set preview size and make any resize, rotate or
            // reformatting changes here

            // start preview with new settings
            try {
                camera.setPreviewDisplay(hd);
                camera.startPreview();

            } catch (Exception e){
                Log.d(TAG, "Error starting camera preview: " + e.getMessage());
            }
        }
    }
    

	 

	/** Handles data for jpeg picture */
	PictureCallback jpegCallback = new PictureCallback() {
		public void onPictureTaken(byte[] data, Camera camera) {
			try {
		        String url = LoginActivity.SITE+"/upload_photo/";
			    HttpClient httpclient = new DefaultHttpClient();
			    HttpPost httpost = new HttpPost(url);
			    
				ByteArrayBody bab = new ByteArrayBody(data, "foto.jpg");
				MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
		        entity.addPart("username", new StringBody(username));
		        
		        entity.addPart("photo",bab); 
		        entity.addPart("identifier", new StringBody(id));
				
				httpost.setEntity(entity);
				
		        // Execute HTTP Post Request
		        HttpResponse response = httpclient.execute(httpost);
//		        FileOutputStream fos = new FileOutputStream("/sdcard/oi.jpg");
//		        fos.write(data);
//		        fos.close();
		        
		        
//		        BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
//				String sResponse;
//				StringBuilder s = new StringBuilder();
//				String respo="";
//				while ((sResponse = reader.readLine()) != null) {
//					respo=respo.concat(sResponse);
//				}
//				Log.e("CAMERAAAAA", respo);
//				fos = new FileOutputStream("/sdcard/respos.html");
//		        fos.write(respo.getBytes("UTF-8"));
//		        fos.close();
				
			} catch (Exception e) {
				Toast.makeText(ExemploCameraActivity.this, "Jpg callback" + e.getMessage(), Toast.LENGTH_LONG).show();
			} finally{
				ExemploCameraActivity.this.finish();
			}
		}
	};
}